//
//  EPCOAuthController.swift
//  Weibo
//
//  Created by LioWu on 09/04/2017.
//  Copyright © 2017 MyGit. All rights reserved.
//

import UIKit
import SVProgressHUD

class EPCOAuthController: UIViewController {

    private lazy var webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        
        view.backgroundColor = UIColor.white
        
        title = "登录新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "返回", target: self, action: #selector(back), isBack:true)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "自动填充", target: self, action: #selector(autoFill))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        webView.delegate = self
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(EPCAppKey)&redirect_uri=\(EPCRedirectURI)"
        
        guard let url = URL.init(string: urlString) else {
            return
        }
        
        let req = URLRequest.init(url: url)
        
        webView.loadRequest(req)

    }
    
    
    /// back: dismiss controller
    @objc fileprivate func back() {
        
        SVProgressHUD.dismiss()
        
        self.dismiss(animated: true, completion: nil)
    }
    
    
    /// auto fill userId/passwd by js
    @objc fileprivate func autoFill() {
        let js = "document.getElementById(\"userId\").value = 15712079019; " + "document.getElementById(\"passwd\").value = \"Wlf070922\";"
        
        webView.stringByEvaluatingJavaScript(from: js)
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension EPCOAuthController: UIWebViewDelegate {

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if request.url?.absoluteString.hasPrefix(EPCRedirectURI) == false {
            return true
        }
        
        if request.url?.query?.hasPrefix("code=") == false {
            
            back()
            
            return false
        }
        
        guard let code = request.url?.query?.substring(from: "code=".endIndex) else {
                return false
        }
        
        print(code)
        
        EPCNetworking.shareManager.requestToken(authCode: code) { (isSuccess) in
            
            if isSuccess == false {
                
                SVProgressHUD.showError(withStatus: "网络请求失败！")
                
            } else {
                
                NotificationCenter.default.post(name: NSNotification.Name(EPCUserLoginSuccessNotification), object: nil)
                
                self.back()
            }
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
